<template>
  <div id="map"></div>
  <div class="fitbtn">
    <el-button type="primary" @click="zoomtoswitzerland">zoomtoswitzerland</el-button>
    <el-button type="primary" @click="zoomtolausanne">zoomtolausanne</el-button>
    <el-button type="primary" @click="centerlausanne">centerlausanne</el-button>
  </div>
</template>

<script setup>
import Tianditu from '@/utils/Tianditu'
import { onMounted, shallowRef } from 'vue'
import { Map, View } from 'ol'
import VectorSource from 'ol/source/Vector'
import VectorLayer from 'ol/layer/Vector'
import GeoJSON from 'ol/format/GeoJSON'

const TDT = new Tianditu()
const vecLyrGrp = TDT.createTileLayerGroup('vec', true)
let map = shallowRef(null)
let source = null
onMounted(() => {
  map.value = new Map({
    target: 'map',
    view: new View({
      center: [6.6339863, 46.5193823],
      zoom: 4
    }),
    layers: [vecLyrGrp]
  })

  // 加载geojson数据
  source = new VectorSource({
    url: 'source/AdvancedViewPositioning.json',
    format: new GeoJSON()
  })
  const geonjsonLayer = new VectorLayer({
    source: source
  })
  map.value.addLayer(geonjsonLayer)
})

function zoomtoswitzerland() {
  const view = map.value.getView()
  const feature = source.getFeatures()[0]
  const polygon = feature.getGeometry()
  console.log(polygon)
  view.fit(polygon, { duration: 1000, padding: [50, 50, 50, 50] })
}

function zoomtolausanne() {
  const view = map.value.getView()
  const feature = source.getFeatures()[1]
  const point = feature.getGeometry()
  view.fit(point, { duration: 1000, padding: [170, 50, 30, 150] })
}

// 定位到指定的中心
function centerlausanne() {
  const view = map.value.getView()
  const feature = source.getFeatures()[1]
  const point = feature.getGeometry()
  const size = map.value.getSize()
  view.centerOn(point.getCoordinates(), size, [570, 500])
}

</script>

<style scoped>
#map {
  height: 100%;
  width: 100%;
}

.fitbtn {
  position: absolute;
  top: 10px;
  right: 10px;
}
</style>